package serverTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class TestServer {
	ServerSocket server = null;
	Socket client = null;
	BufferedReader in = null;
	PrintWriter out = null;
	Scanner input = new Scanner(System.in);
	
	public TestServer(int port) { 
		try {
			server = new ServerSocket(port); 
		} catch (IOException e) {
			System.out.println("Could not listen on port " + port); System.exit(-1);
		}
		
		System.out.println("Serwer otwarty");
	}
	
	public static void main (String[] args) {
		int port;
		try {
			//nie ma co wpisywac tego za kazdym razem :D
			port = 44; //Integer.parseInt(args[0]);
		} catch (NumberFormatException ex) {System.out.println("Podaj poprawny numer portu"); return;}
		
		TestServer ts = new TestServer(port);
		while (true) {
			try {
				try {
					ts.client = ts.server.accept();
				} catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); }
				try {
					ts.in = new BufferedReader(new InputStreamReader(ts.client.getInputStream()));
					ts.out = new PrintWriter(ts.client.getOutputStream(), true);
				} catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); }
				
				System.out.println("Polaczono z klientem");
				ts.out.println("365000");
				ts.out.println("0Ah4s0dKc200");
				
				while (true) {
					String text = ts.input.nextLine();
					//jesli wpiszesz r i <enter> to wczyta to co wyslal klient
					//wszystko inne po prostu sie wysyla
					if (text.substring(0,1).equals("r") && text.length() == 1) {
						try {
							System.out.println(ts.in.readLine());
						} catch (IOException e) { e.printStackTrace(); }
					} else
						ts.out.println(text);
				}
			} catch (Exception ex) {System.out.println("error. please reconnect");}
		}
	}
	
}
